<template>
  <view class="page-container">
    <HeaderBar
        title="包车详情"
        :navBarBgc="navBarBgc"
		@click="pageBack"
    ></HeaderBar>
    <view class="product-name">{{yudingData.routeName}}-{{trafficInfo.name}}</view>
    <view class="productname"> 私享包车，舒适出行 </view>
	<view class="tabs-container">
	  <view
		  v-for="(tabItem, tabIndex) in tabList"
		  :key="tabIndex"
		  class="tab"
		  @click="handleChoiceTab(tabIndex)"
	  >
		<img v-show="tabIndex === tabActiveIndex" class="img" src="http://img.jowong.com/aba/2025-03-26/未命名 -1_11_1742951965378.png" />
		<text :class="['tab-title', tabIndex === tabActiveIndex ? 'active-tab-title' : '']">{{ tabItem }}</text>
	  </view>
	</view>
	<view class="product-details">
		<view class="reservation-module-title">
			<i class="iconfont icon-yuyuejilu1"></i>
			<text class="title">产品详情</text>
			<image class="border-img" src="http://img.jowong.com/aba/2025-03-27/图层 554_1743061625989.png"></image>
		</view>
	
	    <!-- 车型说明 -->
	    <view class="info-section">
	      <view class="info-title">🚗 车型说明:</view>
	      <view class="info-text">{{ carTypeInfo }}</view>
	    </view>
		<view v-if="isExpanded">
			<!-- 第一张汽车图片 --> 
			<img src="http://img.jowong.com/aba/2025-03-28/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240402155212_1743149535847.jpg" class="car-image"/>
		
			<!-- 第二张汽车图片 -->
			<img src="http://img.jowong.com/aba/2025-03-28/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20240402155212_1743149535847.jpg" class="car-image"/>
		
			<!-- 行程说明 -->
			<view class="info-section">
			  <view class="info-title">📍 行程说明:</view>
			  <view class="info-text">{{ tripInfo }}</view>
			</view>
		
			<!-- 补充说明 -->
			<view class="info-section">
			  <view class="info-title">📝 补充说明:</view>
			  <view class="info-text">{{ extraInfo }}</view>
			</view>
		</view>
	    
	
	    <!-- 展开/收起按钮 -->
	    <view class="toggle-button" @click="toggleExpand">
	      {{ isExpanded ? "收起全部 ▲" : "展开全部 ▼" }}
	    </view>
    </view>
	
    <view class="page-content">
      <view class="reservation-module-title">
        <i class="iconfont icon-yuyuejilu1"></i>
        <text class="title">预约选择</text>
        <image class="border-img" src="http://img.jowong.com/aba/2025-03-27/图层 554_1743061625989.png"></image>
      </view>
      <view class="first-title">使用日期</view>
      <!--  使用日期选择  -->
      <view class="ticket-choose-date-container">
        <view
            v-for="(item,index) in dateList"
            :key="index"
			@click="chooseDateId(item.date)"
            :class="['date-item',item.date === chooseDate ? 'active-date-item' : '']"
        >
          <view>{{item.title}}</view>
          <view>{{item.label}}</view>
        </view>
        <view class="more-date flex flex-center flex-1" @click="open">
          <wd-calendar v-model="value" :min-date="minDate" @confirm="handleConfirm">
            <view class="left-container">
          	<view>更多</view>
          	<view>日期</view>
            </view>
          </wd-calendar>
          <wd-icon name="arrow-right" size="18px" color="#181818"></wd-icon>
        </view>
      </view>
      <view class="first-title">车型</view>
      <!--   车型选择   -->
      <view class="car-type-container">
        <view
            v-for="(item,index) in trafficInfo.carModels"
            :key="index"
            @click="chooseCar(item,index)"
            :class="['car-type-item','mb30','mr20',index === choiceCarTypeId ? 'active' : '']"
        >
          {{getName(item.code)}}({{item.seats}})座
        </view>
      </view>
      <view class="first-title">发车时间</view>
      <!--  发车时间列表    -->
      <view class="car-type-container">
        <view
            v-for="(item,index) in timeSlotList"
            :key="index"
			@click="!isTimePassed(item) && chooseTime(item, index)"
            :class="['car-type-item','mb30','mr20',index === choiceCarTimeId ? 'active' : '',isTimePassed(item) ? 'disabled' : '']"
        >
          <text class="pr10 start-time">{{item}} - 发车</text> 
        </view>
      </view>
    </view>
	<view style="height: 300rpx;"></view>
    <view class="bottom-container">
      <view class="buyer-notice-container">
        <view class="buyer-notice-content">无需取票 I 有条件退</view>
        <view class="buyer-notice-tip">购买须知></view>
      </view>
      <view class="top-container flex ">
        <view class="price">￥ {{yudingData.trafficInfodetail.price}}</view>
        <view class="right-container">
         <!-- <view class="price-detail-tip">
            <text>明细</text>
            <wd-icon name="arrow-down" size="22px"></wd-icon>
          </view> -->
          <view class="btn" @click="gotoReserve">去预定</view>
        </view>
      </view>
      <view class="safe-content" :style="{height:bottomSafeInsetNumber + 'px'}"></view>
    </view>
  </view>
</template>

<script setup>
  import { ref } from "vue";
  import dayjs from "dayjs";
  import {commonWordList} from "@/api/system";
  import HeaderBar from "@/trafficSubPack/components/headerBar/index.vue";
  import {trafficDetail} from "@/trafficSubPack/api/trafficHome";

  const tabList = ref(["详情", "预约选择", "购买须知"]);
  const tabActiveIndex = ref(0);
  
  const navBarBgc = "linear-gradient(180deg, rgba(186,209,194,1) 0%, rgba(207,223,212,1) 33%, rgba(230,238,233,1) 100%);";
  const dateList = ref([]);
  const startDate = ref(dayjs().format("YYYY-MM-DD"));
  const chooseDate = ref(dayjs().format("YYYY-MM-DD"));
  const minDate =Date.now() 
  const value = ref(Date.now())
  const trafficInfo = ref([]) 
  const timeSlotList = ref([]);
  const choiceCarTypeId = ref(0);
  const choiceCarTimeId = ref();
  const bottomSafeInsetNumber = ref(0);
  
  const pageBack = () =>{
  	  uni.navigateBack()
  }
  
  // 说明信息
  const carTypeInfo = ref("5座轿车(现代/速腾/宝马同等级)，7座轿车(别克同等级)，9座轿车(福通JMC/大通同等级)，具体车型以所选套餐为准");
  const tripInfo = ref("5座轿车(现代/速腾/宝马同等级)，7座轿车(别克同等级)，9座轿车(福通JMC/大通同等级)，具体车型以所选套餐为准");
  const extraInfo = ref("5座轿车(现代/速腾/宝马同等级)，7座轿车(别克同等级)，9座轿车(福通JMC/大通同等级)，具体车型以所选套餐为准");
  
  const yudingData =reactive({
	  trafficInfo:[],
	  chooseDate:chooseDate || '',
	  trafficInfodetail:{},
	  choiceCarTime:'',
	  routeId:'',
	  routeName:'',
	  carModel:[]
  })
  const gettrafficDetail = (id)=>{
  	  trafficDetail(id).then(res=>{
  		  // console.log('trafficDetail',res);
        let {result} = res;
  		  trafficInfo.value = result
  	      if (result.carModels){
			  timeSlotList.value = JSON.parse(result.carModels[0].departureTime)
			  yudingData.trafficInfo = result
			  yudingData.trafficInfodetail = result.carModels[0]
			  // yudingData.choiceCarTime = timeSlotList.value[0] 
		  } 
  	  })
  }
  // 使用日期
  const chooseDateId = (data)=>{
    choiceCarTimeId.value = ''
	yudingData.choiceCarTime = ''
    chooseDate.value = data;
	yudingData.chooseDate = data
    value.value = new Date(data).getTime() 
  }
const isTimePassed = (timeStr) => {
  if(yudingData.chooseDate != dayjs().format("YYYY-MM-DD")){
	return false
  } else {
	const [hours, minutes] = timeStr.split(":").map(Number);
	const now = new Date();
	const compareTime = new Date();
	compareTime.setHours(hours, minutes, 0, 0);
	return now > compareTime; 
  }
};
  
 const queryCommonWordList = async () => {
 	await commonWordList({keys:"CAT_MODEL_TRAFFIC"}).then(res => { 
 		yudingData.carModel = res.result.CAT_MODEL_TRAFFIC
 	}); 
 }; 
 const getName = (val)=>{
 	return yudingData.carModel.find(item => item.code == val)?.name || '';
 } 
  // 车型
  const chooseCar = (data,index)=>{
    choiceCarTimeId.value = ''
	yudingData.choiceCarTime = ''
	timeSlotList.value = JSON.parse(data.departureTime)
	trafficInfo.value.price = data.price
    choiceCarTypeId.value = index;
	yudingData.trafficInfodetail = data 
  }
  // 发车时间
  const chooseTime = (data,index)=>{
    choiceCarTimeId.value = index;
	yudingData.choiceCarTime = data 
  }
  
  const handleChoiceTab = (index) => {
    tabActiveIndex.value = index;
  };
  
  // 控制展开/收起
  const isExpanded = ref(false);
  const toggleExpand = () => {
    isExpanded.value = !isExpanded.value;
  };
  
  const gotoReserve =()=>{
	  if(yudingData.choiceCarTime == '') {
		  uni.showToast({
			title:'未选择发车时间',
			icon:"error"
		  })
		  return ;
	  }
  	console.log('yudingData',yudingData); 
     // 将 yudingData 转换为 JSON 字符串
  	const yudingDataJson = JSON.stringify(yudingData);
  
  	// 使用 encodeURIComponent 对 JSON 字符串进行编码
  	const encodedYudingData = encodeURIComponent(yudingDataJson);
  
  	// 跳转到目标页面并传递参数
  	uni.navigateTo({
  	  url: `/trafficSubPack/pages/charteredBusDetail/orderWrite?yudingData=${encodedYudingData}`
  	});
  }

  const generateDateArray = (startDate, count) =>  {
    const dateArray = [];
    const weekDays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    const today = new Date(); // 当前日期
    const todayStr = today.toISOString().split("T")[0]; // 格式化 YYYY-MM-DD

    for (let i = 0; i < count; i++) {
      const dateObj = new Date(startDate);
      dateObj.setDate(dateObj.getDate() + i); // 计算每一天

      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1; // 月份从 0 开始
      const day = dateObj.getDate();
      const weekDay = weekDays[dateObj.getDay()];
      const dateStr = `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;

      // 计算 title
      let title = weekDay;
      if (dateStr === todayStr) {
        title = "今天";
      } else {
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);
        if (dateStr === tomorrow.toISOString().split("T")[0]) {
          title = "明天";
        } else {
          const afterTomorrow = new Date(today);
          afterTomorrow.setDate(today.getDate() + 2);
          if (dateStr === afterTomorrow.toISOString().split("T")[0]) {
            title = "后天";
          }
        }
      }

      // 组装对象
      dateArray.push({
        label: `${month}月${day}日`,
        date: dateStr,
        title: title,
      });
    }
    dateList.value = dateArray;
  }
  
  function handleConfirm({ value }) {  
  	// 将时间戳转换为 Date 对象
  	let date = new Date(value); 
  	// 提取年、月、日，并格式化为 YYYY-MM-DD
  	let year = date.getFullYear(); // 获取年份
  	let month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
  	let day = String(date.getDate()).padStart(2, '0'); // 获取日期并补零
  	const datetime = `${year}-${month}-${day}`; 
  	chooseDateId(datetime)
  	generateDateArray(datetime,4); 
  } 
  onLoad((options) => {
	queryCommonWordList()
	if(options){
	   // console.log('mnbvcxz',options.id);
	   gettrafficDetail(options.id)
	   yudingData.routeId = options.routeId
	   yudingData.routeName = options.name
	} 
    generateDateArray(startDate.value,4);
    bottomSafeInsetNumber.value = uni.getSystemInfoSync().safeAreaInsets.bottom;
  });
</script>

<style lang="scss" scoped>
  .page-container {
    width: 100%;
    min-height: 100vh;
    .product-name {
      font-size: 42rpx;
      padding: 40rpx 27rpx;
      font-weight: bold;
      background: linear-gradient(180deg, rgba(231,239,234,1) 0%, rgba(239,244,241,1) 15%, rgba(255,255,255,1) 100%);
    }
	.productname{
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 29rpx;
        padding: 0rpx 27rpx;
		color: #1B9C61;
		line-height: 28rpx;
	}
	.product-details {
	  padding:0 20rpx;
	  // background-color: #fff;
	  // border-radius: 10rpx;
	  // box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}
	.tabs-container {
	  display: flex;
	  align-items: center;
	  justify-content: space-around;
	  margin-top: 40rpx;
	  padding:0 19.5rpx 16rpx 19.5rpx;
	  background: #1b9c61;
	  border-top-right-radius: 20rpx;
	  border-top-left-radius: 20rpx;
	  .tab {
	    position: relative;
	    width: 236rpx;
	    height: 82.5rpx;
	    text-align: center;
	    .img {
	      position: absolute;
	      left: 0;
	      bottom: -32rpx;
	      width: 100%;
	      height: 100%;
	    }
	    .tab-title {
	      position: absolute;
	      top:44rpx;
	      left: 0;
	      width: 236rpx;
	      text-align: center;
	      color: #FFFFFF;
	    }
	    .active-tab-title {
	      color: #AA5413;
	      font-weight: bold;
	    }
	    .circle-img {
	      position: absolute;
	      width: 70rpx;
	      height: 16rpx;
	      bottom: -10rpx;
	      left: 50%;
	      margin-left: -35rpx;
	    }
	  }
	}
	.reservation-module-title {
	  position: relative;
	  width: auto;
	  display: flex;
	  margin-top: 70rpx;
	  align-items: flex-end;
	  .icon-yuyuejilu1 {
	    font-size: 36rpx;
	    color: #1b9c61;
	  }
	  .title {
	    font-size: 29rpx;
	    font-weight: bold;
	    color: #2B2B24;
	  }
	  .border-img {
	    position: absolute;
	    bottom: -6rpx;
	    left: 0;
	    width: 153rpx;
	    height: 7rpx;
	  }
	}
	.section-title {
	  font-size: 32rpx;
	  font-weight: bold;
	  padding-bottom: 20rpx;
	  border-bottom: 2rpx solid #ddd;
	}
	
	.info-section {
	  padding: 50rpx 0 20rpx 0;
	}
	
	.info-title {
	  font-size: 28rpx;
	  font-weight: bold;
	}
	
	.info-text {
	  font-size: 26rpx;
	  color: #333;
	  margin: 10rpx 20rpx;
	}
	
	.car-image {
	  width: 100%;
	  // height: 312rpx;
	  margin-bottom: 10rpx;
	  border-radius: 10rpx; 
	}
	
	.toggle-button {
	  text-align: center; 
	  font-family: PingFang SC;
	  font-weight: bold;
	  font-size: 29rpx; 
	  color: #1b9c61;
	  padding: 20rpx 0;
	  cursor: pointer;
	}
    .page-content {
      padding: 0 27.5rpx;
      .reservation-module-title {
        position: relative;
        width: auto;
        display: flex;
        align-items: flex-end;
        .icon-yuyuejilu1 {
          font-size: 36rpx;
          color: #1b9c61;
        }
        .title {
          font-size: 29rpx;
          font-weight: bold;
          color: #2B2B24;
        }
        .border-img {
          position: absolute;
          bottom: -6rpx;
          left: 0;
          width: 153rpx;
          height: 7rpx;
        }
      }
      .first-title {
        padding: 30rpx 0;
        font-size: 29rpx;
        font-weight: bold;
      }
      .ticket-choose-date-container {
        display: flex;
        justify-content: space-between;
        .date-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 166rpx;
          width: 20%;
          border-radius: 10.5rpx;
          font-size: 25rpx;
          margin-right: 14rpx;
          color: #181818;
          background: #EEF0DF;
          overflow: hidden;
        }
        .active-date-item {
          color: #FDFFEB;
          background: #1B9C61;
        }
        .more-date{
          font-size: 25rpx;
        }
      }
      .car-type-container {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .car-type-item {
          font-size: 25rpx;
          padding: 16rpx 34rpx;
          border-radius: 10.5rpx;
          color: #2B2B24;
          background: #EEF0DF;   
	  
	    &.active {
	      background-color: #409EFF;
	      color: #fff;
	      border: none;
	    }
	  
	    &.disabled {
	      background-color: #eee;
	      color: #999;
	      pointer-events: none; // 禁止点击
	    }
	  }
      }
    }
    .active{
      color: #FDFFEB !important;
      background:#1B9C61 !important;
    }
  }
  .bottom-container {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    background: #FDFFEB;
    .buyer-notice-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 25rpx;
      padding: 12rpx 30rpx 12rpx 30rpx;
      background: #eef0df;
      .buyer-notice-content {
        color: #2B2B24;
      }
      .buyer-notice-tip {
        color: #AA5413;
      }
    }
    .top-container {
      justify-content: space-between;
      align-items: center;
      padding: 32rpx 20rpx 0 59rpx;
      .price {
        font-size: 42rpx;
        font-weight: bold;
        color: #AA5413;
      }
      .right-container {
        display: flex;
        align-items: center;
        .price-detail-tip {
          display: flex;
          align-items: center;
          padding-right: 11rpx;
          text {
            font-size: 30rpx;
          }
        }
        .btn {
          border-radius: 10.5rpx;
          font-weight: bold;
          padding: 25rpx 32rpx;
          color: #FDFFEB;
          background: #AA5413;
        }
      }
    }
  }
</style>
